<?php
/**
 * Created by PhpStorm.
 * User: chenishr
 * Date: 2018/7/21
 * Time: 2:48 PM
 */

namespace Hanson\MyVbot\Html;

use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

class Pdfcrowd {
    const domain = 'https://pdfcrowd.com';
    const api = 'https://pdfcrowd.com/form/json/convert/uri/v2/';

    static public function html_to_pdf($src){
        $qiniuSrc = self::_save_to_qiniu($src);
        if(false === $qiniuSrc){
            echo "1\n";
            return false;
        }

        $postData['noCache'] = time();
        $postData['src'] = $qiniuSrc;
        $postData['conversion_source'] = 'uri';

        $res = self::_post_url(self::api,$postData);

        if('ok' != $res['status']){
            echo "2\n";
            return false;
        }

        $reg = '#name=(.*?\.pdf)#';
        preg_match($reg,$res['uri'],$matchs);

        if(!$matchs[1]){
            echo "3\n";
            return false;
        }

        $fileName = $matchs[1];

        $r = file_put_contents('/tmp/' . $fileName,file_get_contents(self::domain . $res['uri']));

        if(false === $r){
            echo "4\n";
            return false;
        }

        return $fileName;
    }

    static private function _save_to_qiniu($src){
        $config = require __DIR__.'/../config.php';
        if(!isset($config['qiniu'])){
            echo "5\n";
            return false;
        }

        $upManager = new UploadManager();
        $auth = new Auth($config['qiniu']['ak'], $config['qiniu']['sk']);
        $token = $auth->uploadToken($config['qiniu']['bucketName']);
        $conents = file_get_contents($src);
        $conents = str_replace('data-src','src',$conents);
        $conents = str_replace('<head>','<head> <meta name="referrer" content="never"> ',$conents);

        list($ret, $error) = $upManager->put($token, 'wechat-article/art-'. time(). '-' . rand(100,99) . '.html', $conents);

        if(null != $error){
            echo "6\n";
            return false;
        }

        return $config['qiniu']['bucketUrl'] . $ret['key'];
    }

    static private function _post_url($url,$postData){
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

        $output = curl_exec($ch);
        curl_close($ch);

        $res = json_decode($output,true);

        return $res;
    }
}